<!--
 * Copyright (c) 2015-2025 http://www.hdphp.cn All rights reserved. 
 * Licensed ( http://www.hdphp.cn/licenses/ )
 * Author: Jack <sophia2152@qq.com>
 * 官方网址: http://www.hdphp.cn
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用。
 * 任何企业和个人不允许对程序代码以任何形式任何目的再发布。
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="50%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, computed, ref, unref } from 'vue';
  import { formSchema } from './admin.data';
  import { createAdmin, updateAdmin } from '/@/api/system/admin';
  import { getRoleSelectList } from '/@/api/system/role';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicForm, useForm } from '/@/components/Form';
  import { useMessage } from '/@/hooks/web/useMessage';

  export default defineComponent({
    name: 'AdminDrawer',
    components: { BasicDrawer, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);

      const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
        labelWidth: 100,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: { lg: 12, md: 24 },
      });

      const [registerDrawer, { closeDrawer, setDrawerProps }] = useDrawerInner(async (data) => {
        const stype = await getRoleSelectList();
        stype.forEach((item) => {
          item.value = item.value.toString();
          return item;
        });
        // 将数据放到下拉框上
        await updateSchema({
          field: 'roles',
          componentProps: {
            mode: 'multiple',
            options: unref(stype),
          },
        });

        resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        if (unref(isUpdate)) {
          setFieldsValue({
            ...data.record,
          });
        }
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '添加管理员' : '编辑管理员'));

      async function handleSubmit() {
        try {
          const values = await validate();
          setDrawerProps({ confirmLoading: true });
          const { createMessage } = useMessage();
          if (unref(isUpdate)) {
            await updateAdmin(values.id, values).then(() => {
              createMessage.success('编辑成功');
            });
          } else {
            await createAdmin(values).then(() => {
              createMessage.success('添加成功');
            });
          }
          emit('success');
          closeDrawer();
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      return {
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
      };
    },
  });
</script>
